package com.shanzmoo.admin.domain;

import cn.hutool.core.collection.CollectionUtil;
import com.shanzmoo.db.sys.entity.UserEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 认证用户
 * @author: Gzhao 2020/11/9
 */
@Data
@Accessors(chain = true)
public class AuthUser implements UserDetails {

    /**
     * 用户id
     */
    private Integer userId;

    /**
     * 账号
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 用户角色列表
     */
    private List<Integer> roleIds;

    /**
     * 用户权限列表
     */
    private Collection<? extends GrantedAuthority> authorities;

    /**
     * 用户状态
     */
    private Boolean status;

    public static AuthUser create(UserEntity userEntity, List<Integer> roleIds, List<String> perms) {
        if (null == userEntity){
            return null;
        }
        List<GrantedAuthority> authorities;
        if (CollectionUtil.isEmpty(perms)){
            authorities = Collections.emptyList();
        } else {
            authorities = perms.stream()
                    .map(permission -> new SimpleGrantedAuthority(permission))
                    .collect(Collectors.toList());
        }

        return  new AuthUser()
                .setUserId(userEntity.getUserId())
                .setUsername(userEntity.getUsername())
                .setPassword(userEntity.getPassword())
                .setStatus(userEntity.getStatus())
                .setRoleIds(null == roleIds ? Collections.emptyList() : roleIds)
                .setAuthorities(authorities);
    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return status;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
